package com.luck.config;


import cn.hutool.core.util.ObjectUtil;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor;
import feign.Retryer;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

@Configuration
public class FeignConfig {

    private static final String MDCTRACE_ID = "traceId";
    @Bean //日志级别
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
    @Bean
    public Request.Options options() {
        return new Request.Options(10L, TimeUnit.SECONDS, 10L,TimeUnit.SECONDS,false);
    }
    @Bean
    public Retryer retryer() {
        // period：重试初始间隔时间(毫秒)
        // maxPeriod：重试最大间隔时间(毫秒)
        // maxAttempts：最大重试次数，此次数包括首次请求
        return new Retryer.Default(1000, 3000, 3);
    }
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            requestTemplate.header(MDCTRACE_ID, MDC.get(MDCTRACE_ID));
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) (RequestContextHolder.getRequestAttributes());
            String token = requestAttributes.getRequest().getHeader("token");
            if (ObjectUtil.isNotEmpty(token)){
                requestTemplate.header("token",token);
            }
        };
    }
}
